import React, { RefObject } from 'react';
import { ScrollView, View, Text, StyleSheet, Dimensions } from 'react-native';
import VoiceBubble from './VoiceBubble';
import { adapt, adaptFontSize } from '../../ulits/Adapt';

// 消息类型定义
export type MessageType =
  | { type: 'text', text: string }
  | { type: 'voice', filePath: string, duration: number };

interface Props {
  messages: MessageType[];
  scrollViewRef: RefObject<ScrollView | null>;
}

// 根据字数动态调整 maxWidth（用 number，不能用百分比字符串）
function getBubbleWidthStyle(text: string) {
  const screenWidth = Dimensions.get('window').width;
  const len = text.length;
  let maxWidth = screenWidth * 0.4; // 最短40%
  if (len > 8 && len <= 16) maxWidth = screenWidth * 0.55;
  else if (len > 16 && len <= 40) maxWidth = screenWidth * 0.7;
  else if (len > 40) maxWidth = screenWidth * 0.85;
  return { maxWidth };
}

// 消息列表展示组件
const MessageList: React.FC<Props> = ({ messages, scrollViewRef }) => (
  <ScrollView
    ref={scrollViewRef}
    style={{ flex: 1 }}
    contentContainerStyle={styles.container}
    showsVerticalScrollIndicator={false}
    // 内容变化时自动滚动到底部
    onContentSizeChange={() => scrollViewRef.current?.scrollToEnd({ animated: true })}
  >
    {messages.map((msg, idx) =>
      msg.type === 'text'
        ? (
          <View key={idx} style={[styles.bubble, getBubbleWidthStyle(msg.text)]}>
            <Text style={styles.text}>{msg.text}</Text>
          </View>
        ) : (
          // 语音消息用 VoiceBubble 组件
          <VoiceBubble key={idx} filePath={msg.filePath} duration={msg.duration} />
        )
    )}
  </ScrollView>
);

const styles = StyleSheet.create({
  container: {
    paddingTop: adapt(15),
    paddingRight: adapt(15),
    alignItems: 'flex-end',
    paddingBottom: adapt(15),
  },
  bubble: {
    backgroundColor: 'rgb(149,236,105)',
    borderRadius: adapt(16),
    minWidth: adapt(60),
    marginBottom: adapt(8),
    paddingHorizontal: adapt(12),
    paddingVertical: adapt(10),
    justifyContent: 'center',
    alignItems: 'flex-start',
    alignSelf: 'flex-end',
  },
  text: {
    color: '#fff',
    fontSize: adaptFontSize(18),
    flexWrap: 'wrap',
  },
});

export default MessageList;